/**
 * Created by sun on 15-3-10.
 */

var SHAKE_THRESHOLD = 2000;
var SHAKE_DURATION = 2000;
var last_update = 0;
var x = y = z = last_x = last_y = last_z = 0;
var callback;
var handle_power = true;

/**pass callback*/
function init(_callback) {
    if (window.DeviceMotionEvent) {
        callback = _callback;
        window.addEventListener('devicemotion', deviceMotionHandler, false);
    } else {
        alert('not support mobile event');
    }
}
function deviceMotionHandler(eventData) {
    var acceleration = eventData.accelerationIncludingGravity;
    var curTime = new Date().getTime();
    if ((curTime - last_update) > 100) {
        var diffTime = curTime - last_update;
        last_update = curTime;
        x = acceleration.x;
        y = acceleration.y;
        z = acceleration.z;
        var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

        if (speed > SHAKE_THRESHOLD && handle_power) {
            callback();
            //test mode
            handle_power = true;
            resumePower();
        }
        last_x = x;
        last_y = y;
        last_z = z;
    }
}

/**avoid shaking too frequently*/
function resumePower(){
    setTimeout(function(){
        handle_power = true;
    }, SHAKE_DURATION);
}